/**
 *
 */
package persistence;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * The Class XMLUtils.
 * @author doralt
 */
public class XMLUtils {
	
	private static final XStream xstream = new XStream(new DomDriver());

    /**
     * serializes an object into XML string representation
     * using the Xstream package.
     *
     * @param obj the object to serialize
     * @return the serialized object
     */
	public static String serialize(final Object obj) {
        return xstream.toXML(obj);
    }

    /**
     * deserializes an object from its xml string representation
     * using the Xstream package.
     *
     * @param serialized the serialized object to deserialize
     * @return the constructed object
     */
    public static Object deserialize(final String serialized) {
        return xstream.fromXML(serialized);
    }
    
    
    /**
     * Load database.
     * @param file the file
     * @return the forum object created from database
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static Object loadDB(String file) throws IOException{
        FileReader tFileReader = new FileReader(new File(file));
        BufferedReader tBufReader = new BufferedReader(tFileReader);
        String tStr = "";
        while (tBufReader.ready()) {
            tStr += tBufReader.readLine();
        }
        Object tobj = XMLUtils.deserialize(tStr);
        return tobj;
    }

    
    /**
     * Save database.
     *
     * @param obj object need to be saved
     * @param file the file to save to
     *
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public static void saveDB(Object obj, String file) throws IOException {
        String tXmlStr = serialize(obj);
        //String filename = file.getCanonicalPath();
        writeToFile(tXmlStr, file);
    }



    /**
     * Write to file.
     *
     * @param s the string we want to write to file
     * @param filename the filename
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private static void writeToFile(String s, String filename) throws IOException{
        // open file for output
        FileWriter tFileWriter = new FileWriter(filename);
        BufferedWriter tBufWriter = new BufferedWriter(tFileWriter);
        tBufWriter.write(s);
        // close the file
        tBufWriter.close();
    }    
}
